/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* prev = head;
        while (fast && fast->next)
        {
            prev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        prev->next = nullptr;
        return mergeList(sortList(head), sortList(slow));
    }
    ListNode* mergeList(ListNode* head1, ListNode* head2)
    {
        if (head1 == nullptr) return head2;
        if (head2 == nullptr) return head1;

        ListNode* newhead = new ListNode(-1);
        ListNode* prev = newhead;

        ListNode* cur1 = head1;
        ListNode* cur2 = head2;
        while (cur1 && cur2)
        {
            if (cur1->val < cur2->val)
            {
                prev = prev->next = cur1;
                cur1 = cur1->next;
            }
            else
            {
                prev = prev->next = cur2;
                cur2 = cur2->next;
            }
        }
        if (cur1) prev->next = cur1;
        if (cur2) prev->next = cur2;
        prev = newhead->next;
        delete newhead;
        return prev;
    }
};